package com.tyjc.lottery.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.welcome.WelcomeActivity;
import com.fyzk.bean.WXLoginResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.CountDownUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.TopTitleView;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/4/24.
 * <p>
 * 微信回调activity（微信开放平台有个 不成文的规定（文档里没有说明），就是回调的Activity必须是：你的包名+.wxapi.WXEntryActivity.java）
 */
@ContentView(R.layout.ac_wxlogin)
public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {

    @ViewInject(R.id.wxlogin_registe_ll)
    private LinearLayout registe_ll;

    @ViewInject(R.id.wxlogin_login_bg)
    private ImageView login_bg;

    @ViewInject(R.id.wxlogin_topview)
    private TopTitleView topView;

    @ViewInject(R.id.wxlogin_binduser_rb)
    private RadioButton bindUser_rb;

    @ViewInject(R.id.wxlogin_registe_rb)
    private RadioButton registe_rb;

    @ViewInject(R.id.wxlogin_phone_til)
    private TextInputLayout phone_til;

    @ViewInject(R.id.wxlogin_phone_et)
    private EditText phone_et;

    @ViewInject(R.id.wxlogin_verify_et)
    private EditText validateCode_et;

    @ViewInject(R.id.wxlogin_verify_btn)
    private TextView validateCode_btn;

    @ViewInject(R.id.wxlogin_login_btn)
    private TextView login_tv;

    private final int binduserType = 0;
    private final int registeType = 1;
    private int type = binduserType;

    private String code = "";
    private String unionid = "";
    private CountDownUtils countDownUtils;
    private final int countDownTime = 60;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((App) this.getApplication()).getWXApi().handleIntent(getIntent(), this);
        initView();
    }

    private void initView() {
        countDownUtils = new CountDownUtils(countDownTime * 1000, 1000, validateCode_btn);
        topView.setOnTitleClickListener(this);
//        registe_ll.setVisibility(View.GONE);
//        login_bg.setVisibility(View.VISIBLE);

        bindUser_rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    phone_til.setHint("输入要绑定账号的手机号");
//                    phone_et.setHint("输入要绑定账号的手机号");
                    login_tv.setText("绑定并登录");
                    type = binduserType;
                    validateCode_et.setText("");
                }

            }
        });

        registe_rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    phone_til.setHint("输入要注册的手机号");
//                    phone_et.setHint("输入要注册的手机号");
                    login_tv.setText("绑定并注册");
                    type = registeType;
                    validateCode_et.setText("");
                }

            }
        });

        validateCode_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validatePhone()) {
                    if (type == binduserType) {
                        requestBindUserVerifyCode();
                    } else {
                        requestRegisteVerifyCode();
                    }
                }
            }
        });

        login_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loginYanZhengVerify()) {
                    if (type == binduserType) {
                        requestWXBindUser();
                    } else {
                        requestWXRegiste();
                    }

                }
            }
        });
    }

    @Override
    public void onReq(BaseReq baseReq) {
        LogUtil.d("onReq");
    }

    @Override
    public void onResp(BaseResp baseResp) {
        LogUtil.d("onResp");
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                LogUtil.d("授权成功 " );
                if(null!=baseResp.transaction){
                    if(baseResp.transaction.equals("webpage")){
                        WXEntryActivity.this.finish();
                    }else if(baseResp.transaction.equals("img")){
                        WXEntryActivity.this.finish();
                    }
                }else{
                    code = ((SendAuth.Resp) baseResp).code; //即为所需的code
                    requestWXLogin(code);
                }

//                getAccess_token(codeValue);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                LogUtil.d("用户拒绝授权");
                finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                LogUtil.d("用户拒绝授权");
                finish();
                break;
            default:
                break;
        }
    }

    /**
     *  微信登录
     */
    private void requestWXLogin(String code) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("codeValue", code);
            httpPostJson(CommandUtil.WXLOGIN, Commands.WXLOGIN,
                    request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     *  微信绑定已有账号
     */
    private void requestWXBindUser() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("unionid", unionid);
            request_json.put("phone", phone_et.getText().toString());
            request_json.put("validateCode", validateCode_et.getText().toString());
            httpPostJson(CommandUtil.WXBINDUSER, Commands.WXBINDUSER,
                    request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     *  微信注册新账号
     */
    private void requestWXRegiste() {
        try {
            JSONObject request_json = new JSONObject();
//            request_json.put("codeValue", codeValue);
            request_json.put("unionid", unionid);
            request_json.put("phone", phone_et.getText().toString());
            request_json.put("validateCode", validateCode_et.getText().toString());
            httpPostJson(CommandUtil.WXREGISTER, Commands.WXREGISTER,
                    request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     *  获取绑定账号验证码
     */
    private void requestBindUserVerifyCode() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("mobilePhone", phone_et.getText().toString());
            httpPostJson(CommandUtil.BINDWXVALIDATECODE, Commands.BINDWXVALIDATECODE, request_json,
                    true);
        } catch (JSONException e) {

        }
    }

    /**
     *  获取注册验证码
     */
    private void requestRegisteVerifyCode() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("mobilePhone", phone_et.getText().toString());
            httpPostJson(CommandUtil.PHONE_VERIFICATION_NEW, Commands.PHONE_VERIFICATION_NEW,
                    request_json,
                    true);
        } catch (JSONException e) {

        }
    }

    WXLoginResponse loginResponse;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.WXLOGIN:
            case CommandUtil.WXBINDUSER:    // 绑定已有账号
            case CommandUtil.WXREGISTER:    // 微信注册
                loginResponse = JSON.parseObject(resultBean.getData(), WXLoginResponse.class);
                AppToast.getToast().show("登录成功");
                MySharedPreferences.getInstance().setUserNo(loginResponse.getUserno());
                MySharedPreferences.getInstance().setUserName(loginResponse.getUsername());
                MySharedPreferences.getInstance().setLoginStatus(true);
                MySharedPreferences.getInstance().setAuthToken(loginResponse.getAccessToken());
                MySharedPreferences.getInstance().setAlias(loginResponse.getAlias());
                MySharedPreferences.getInstance().setPhotoUrl(loginResponse.getPhotoUrl());
                if (LoginActivity._instance != null) {
                    LoginActivity._instance.finish(); // 关闭登录界面
                }
                finish();   // 微信登录成功
                break;
            case CommandUtil.BINDWXVALIDATECODE:
            case CommandUtil.PHONE_VERIFICATION_NEW:
                countDownUtils.start();
                break;
            default:
                break;
        }
    }

    protected void onFailure(int requestCode, String errorCode, String message) {

    }

    @Override
    protected void onFailure(StringResultBean resultBean, int requestCode, String errorCode, String message) {
        switch (requestCode) {
            case CommandUtil.WXLOGIN:
                if (errorCode.equals("40002")) {    // 该微信账号未注册
                    loginResponse = JSON.parseObject(resultBean.getData(), WXLoginResponse.class);
                    unionid = loginResponse.getUnionid();
//                    showSureDialog("该微信账号未注册或未绑定已有账号!");
                } else {
                    AppToast.getToast().show(message);
                }
//                registe_ll.setVisibility(View.VISIBLE);
//                login_bg.setVisibility(View.GONE);
                break;
            default:
                AppToast.getToast().show(message);
                break;
        }
    }

    /**
     * 登录确认
     *
     * @return
     */
    private boolean loginYanZhengVerify() {
        if (!validatePhone()) {
            return false;
        }
        if (isNull(validateCode_et)) {
            AppToast.getToast().show("验证码不能为空！");
            return false;
        }
        return true;
    }

    /**
     * 验证手机号
     *
     * @return
     */
    private boolean validatePhone() {
        String phoneNum = "";
        phoneNum = phone_et.getText().toString();
        if (phoneNum.length() != 11) {
            AppToast.getToast().show("手机号格式不正确！");
            return false;
        }
        return true;
    }

    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null
                || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }

        return false;
    }

    @Override
    public void onLeftClick() {
        Intent intent = new Intent(this,WelcomeActivity.class);
        this.startActivity(intent);
        super.onLeftClick();
    }

    //    SureDialog sureDialog;
//    /**
//     * 确认对话框
//     */
//    public void showSureDialog(String message) {
//
//        SureDialog.OnDialogOKCancleClickListener listener = new SureDialog
// .OnDialogOKCancleClickListener() {
//
//            @Override
//            public void onOKClick() {
//
//                sureDialog.dismiss();
//            }
//
//            @Override
//            public void onCancleClick() {
//                sureDialog.dismiss();
//            }
//        };
//
//        sureDialog = new SureDialog(this, listener, message, "", "确定");
//
//        sureDialog.show();
//    }
}
